<template>
  <div class="security-page page-container">
    <div class="security-wrapper">
      <!-- 内容区域 -->
      <div class="content">
        <a-spin :spinning="loading">
          <div class="form-section">
            <a-form :form="form" @submit="handleSubmit">
              <!-- 原密码 -->
              <a-form-item label="原密码">
                <a-input-password
                  v-decorator="[
                    'oldPassword',
                    {
                      rules: [
                        { required: true, message: '请输入原密码' },
                        { min: 6, message: '密码长度不能少于6位' }
                      ]
                    }
                  ]"
                  placeholder="请输入原密码"
                >
                  <a-icon slot="prefix" type="lock" />
                </a-input-password>
              </a-form-item>

              <!-- 新密码 -->
              <a-form-item label="新密码">
                <a-input-password
                  v-decorator="[
                    'newPassword',
                    {
                      rules: [
                        { required: true, message: '请输入新密码' },
                        { min: 6, message: '密码长度不能少于6位' },
                        { validator: validateNewPassword }
                      ]
                    }
                  ]"
                  placeholder="请输入新密码"
                >
                  <a-icon slot="prefix" type="safety" />
                </a-input-password>
              </a-form-item>

              <!-- 确认新密码 -->
              <a-form-item label="确认新密码">
                <a-input-password
                  v-decorator="[
                    'confirmPassword',
                    {
                      rules: [
                        { required: true, message: '请确认新密码' },
                        { validator: validateConfirmPassword }
                      ]
                    }
                  ]"
                  placeholder="请再次输入新密码"
                >
                  <a-icon slot="prefix" type="check-circle" />
                </a-input-password>
              </a-form-item>

              <!-- 密码强度提示 -->
              <div class="password-strength" v-if="passwordStrength">
                <div class="strength-label">密码强度：</div>
                <div class="strength-bar">
                  <div 
                    class="strength-indicator" 
                    :class="strengthClass"
                    :style="{ width: strengthWidth }"
                  ></div>
                </div>
                <div class="strength-text" :class="strengthClass">{{ strengthText }}</div>
              </div>

              <!-- 提交按钮 -->
              <div class="form-buttons">
                <a-button type="primary" html-type="submit" :loading="submitting" block>
                  确认修改
                </a-button>
              </div>
            </a-form>

            <!-- 密码要求说明 -->
            <div class="password-tips">
              <h4>密码要求：</h4>
              <ul>
                <li>长度至少6位</li>
                <li>包含大小写字母</li>
                <li>包含数字</li>
                <li>包含特殊字符更安全</li>
              </ul>
            </div>
          </div>
        </a-spin>
      </div>
    </div>
  </div>
</template>

<script>
import { Form, Input, Button, Icon, message, Spin } from 'ant-design-vue'
import { updatePwd } from '@/api/user'
import md5 from 'md5'
import { mapGetters, mapActions } from 'vuex'

export default {
  name: 'SecuritySettings',
  components: {
    AForm: Form,
    AFormItem: Form.Item,
    AInput: Input,
    AInputPassword: Input.Password,
    AButton: Button,
    AIcon: Icon,
    ASpin: Spin
  },
  data() {
    return {
      loading: false,
      submitting: false,
      passwordStrength: '',
      form: this.$form.createForm(this)
    }
  },
  computed: {
    ...mapGetters('user', ['id']),
    strengthClass() {
      const strengthMap = {
        weak: 'strength-weak',
        medium: 'strength-medium',
        strong: 'strength-strong'
      }
      return strengthMap[this.passwordStrength] || ''
    },
    strengthWidth() {
      const widthMap = {
        weak: '33.33%',
        medium: '66.66%',
        strong: '100%'
      }
      return widthMap[this.passwordStrength] || '0'
    },
    strengthText() {
      const textMap = {
        weak: '弱',
        medium: '中',
        strong: '强'
      }
      return textMap[this.passwordStrength] || ''
    }
  },
  methods: {
    ...mapActions('user', ['logout']),
    goBack() {
      this.$router.push('/user')
    },
    validateNewPassword(rule, value, callback) {
      if (value) {
        // 检查密码强度
        let strength = 'weak'
        let score = 0

        if (value.length >= 8) score++
        if (/[A-Z]/.test(value)) score++
        if (/[a-z]/.test(value)) score++
        if (/[0-9]/.test(value)) score++
        if (/[^A-Za-z0-9]/.test(value)) score++

        if (score >= 4) {
          strength = 'strong'
        } else if (score >= 3) {
          strength = 'medium'
        }

        this.passwordStrength = strength

        // 检查是否与原密码相同
        const oldPassword = this.form.getFieldValue('oldPassword')
        if (oldPassword && value === oldPassword) {
          callback('新密码不能与原密码相同')
          return
        }
      } else {
        this.passwordStrength = ''
      }
      callback()
    },
    validateConfirmPassword(rule, value, callback) {
      const newPassword = this.form.getFieldValue('newPassword')
      if (value && value !== newPassword) {
        callback('两次输入的密码不一致')
      } else {
        callback()
      }
    },
    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields(async (err, values) => {
        if (!err) {
          this.submitting = true
          try {
            const params = {
              id: this.id,
              oldPwd: md5(values.oldPassword),
              newPwd: md5(values.newPassword),
              passwordConfirm: md5(values.confirmPassword)
            }
            
            const response = await updatePwd(params)
            if (response && response.code === 200) {
              message.success('密码修改成功，请重新登录')
              // 清除所有缓存并登出
              await this.logout()
              // 跳转到登录页
              this.$router.push('/auth/login')
            } else {
              throw new Error(response?.msg || '密码修改失败')
            }
          } catch (error) {
            message.error(error.message || '密码修改失败，请重试')
          } finally {
            this.submitting = false
          }
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.security-page {
  min-height: 100vh;
  background: #f5f7fa;
  padding-top: 0;
  position: relative;
  z-index: 1;

  .security-wrapper {
    height: 100%;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;

    .content {
      padding: 16px;
      margin-top: 0;

      .form-section {
        background: #fff;
        border-radius: 8px;
        padding: 24px;
        margin-bottom: 16px;

        .password-strength {
          margin: 16px 0;
          padding: 12px;
          background: #f5f7fa;
          border-radius: 4px;

          .strength-label {
            margin-bottom: 8px;
            color: #8c8c8c;
          }

          .strength-bar {
            height: 4px;
            background: #f0f0f0;
            border-radius: 2px;
            overflow: hidden;
            margin-bottom: 8px;

            .strength-indicator {
              height: 100%;
              transition: all 0.3s;

              &.weak {
                background: #ff4d4f;
              }

              &.medium {
                background: #faad14;
              }

              &.strong {
                background: #52c41a;
              }
            }
          }

          .strength-text {
            font-size: 12px;
            color: #8c8c8c;

            &.weak {
              color: #ff4d4f;
            }

            &.medium {
              color: #faad14;
            }

            &.strong {
              color: #52c41a;
            }
          }
        }

        .form-buttons {
          margin-top: 24px;
        }
      }

      .password-tips {
        background: #fff;
        border-radius: 8px;
        padding: 16px;

        h4 {
          color: #8c8c8c;
          font-size: 14px;
          margin-bottom: 8px;
        }

        ul {
          padding-left: 20px;
          margin: 0;

          li {
            color: #8c8c8c;
            font-size: 12px;
            line-height: 1.8;
          }
        }
      }
    }
  }
}

@media screen and (max-width: 768px) {
  .security-page {
    .security-wrapper {
      .content {
        padding: 12px;

        .form-section {
          padding: 16px;
        }
      }
    }
  }
}
</style> 